//
//  XRRegistViewController.m
//  XDLookPic
//
//  Created by xiaorui on 14-4-21.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "RegisterViewController.h"
#include "XDTools.h"

#import "FetterViewController.h"


@interface RegisterViewController (){
    
    UIButton *agreedBnt;
    UIButton *regbnt;
}
@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.titleLabel.text =@"注册";
    
}

//手势处理
-(void)handleSingleTapFrom{
    [nameTextFiel resignFirstResponder];
    [passwordTextFiel resignFirstResponder];
    [secPassWordTextFiel resignFirstResponder];
    [emailTextFiel resignFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initRegisterViews];
    
    
    
}
//初始化注册view
-(void)initRegisterViews{
    mScrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT -UI_STATUS_BAR_HEIGHT -UI_STATUS_BAR_HEIGHT)];
    mScrollView.contentSize=CGSizeMake(UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT -UI_STATUS_BAR_HEIGHT );
    mScrollView.scrollEnabled =YES;
    mScrollView.delegate = self;
    mScrollView.showsVerticalScrollIndicator = NO;
    [self.contentView addSubview:mScrollView];
    
    UITapGestureRecognizer* singleRecognizer;
    singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFrom)];
    singleRecognizer.numberOfTapsRequired = 1; // 单击
    [mScrollView addGestureRecognizer:singleRecognizer];
    
    
    
    
    UIImageView *bgView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 24, UI_SCREEN_WIDTH, 44 *4 +4)];
    bgView.backgroundColor =[UIColor whiteColor];
    bgView.userInteractionEnabled =YES;
    bgView.image =[UIImage imageNamed:@"regist.png"];
    [mScrollView addSubview:bgView];
    
    UIImageView *imageView1=[[UIImageView alloc]initWithFrame:CGRectMake (15,13,31/2,18)];
    imageView1.image =[UIImage imageNamed:@"useName.png"];
    imageView1.backgroundColor =[UIColor clearColor];
    [bgView addSubview:imageView1];
    nameTextFiel =creatXRTextField(@"输入用户名", CGRectMake(44,5,260,39));
    nameTextFiel.delegate =self;
    nameTextFiel.returnKeyType = UIReturnKeyDone;
    nameTextFiel.borderStyle= UITextBorderStyleNone;
    [bgView addSubview:nameTextFiel];
    UIImageView *lineImageView=[[UIImageView alloc]initWithFrame:CGRectMake(44, 43, UI_SCREEN_WIDTH, 1)];
    lineImageView.backgroundColor =[UIColor clearColor];
    lineImageView.image =[UIImage imageNamed:@"line@2x.png"];
    [bgView addSubview:lineImageView];
    
    
    
    UIImageView *passImageView=[[UIImageView alloc]initWithFrame:CGRectMake(15, 60, 33/2, 37/2)];
    [passImageView setBackgroundColor:[UIColor clearColor]];
    [passImageView setImage:[UIImage imageNamed:@"passdWord"]];
    [bgView addSubview:passImageView];
    passwordTextFiel =creatXRTextField(@"请输入密码", CGRectMake(44,50, 260, 39));
    passwordTextFiel.borderStyle= UITextBorderStyleNone;
    passwordTextFiel.secureTextEntry =YES;
    passwordTextFiel.delegate = self;
    passwordTextFiel.returnKeyType = UIReturnKeyDone;
    [bgView addSubview:passwordTextFiel];
    UIImageView *lineImageView2=[[UIImageView alloc]initWithFrame:CGRectMake(44, 44*2-1, UI_SCREEN_WIDTH, 1)];
    lineImageView2.image =[UIImage imageNamed:@"line@2x.png"];
    [bgView addSubview:lineImageView2];
    
    
    
    UIImageView *secPassImageView=[[UIImageView alloc]initWithFrame:CGRectMake(15, VIEW_POINT_MAX_Y(passwordTextFiel) +12, 17, 18)];
    [secPassImageView setBackgroundColor:[UIColor clearColor]];
    [secPassImageView setImage:[UIImage imageNamed:@"passdWord"]];
    [bgView addSubview:secPassImageView];
    secPassWordTextFiel =creatXRTextField(@"重复密码", CGRectMake(44,44 *2 +7, 260, 39));
    secPassWordTextFiel.borderStyle= UITextBorderStyleNone;
    secPassWordTextFiel.secureTextEntry =YES;
    secPassWordTextFiel.delegate = self;
    secPassWordTextFiel.returnKeyType = UIReturnKeyDone;
    [bgView addSubview:secPassWordTextFiel];
    UIImageView *lineImageView3=[[UIImageView alloc]initWithFrame:CGRectMake(44, 44*3-1, UI_SCREEN_WIDTH, 1)];
    lineImageView3.image =[UIImage imageNamed:@"line@2x.png"];
    //    lineImageView.backgroundColor =[UIColor clearColor];
    [bgView addSubview:lineImageView3];
    
    
    UIImageView *emailImageView=[[UIImageView alloc]initWithFrame:CGRectMake(15, VIEW_POINT_MAX_Y(secPassWordTextFiel) +13, 18, 12)];
    [emailImageView setBackgroundColor:[UIColor clearColor]];
    [emailImageView setImage:[UIImage imageNamed:@"mail.png"]];
    [bgView addSubview:emailImageView];
    emailTextFiel =creatXRTextField(@"输入邮箱", CGRectMake(44,44 *3 +4, 260, 40));
    emailTextFiel.borderStyle= UITextBorderStyleNone;
    emailTextFiel.delegate = self;
    emailTextFiel.returnKeyType = UIReturnKeyDone;
    [bgView addSubview:emailTextFiel];
    
    regbnt=creatXRButton(CGRectMake(10, VIEW_POINT_MAX_Y(bgView) +20, UI_SCREEN_WIDTH -20, 44),nil,nil,nil);
    [regbnt setTitle:@"注册" forState:UIControlStateNormal];
    [regbnt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [regbnt setBackgroundColor:RGBA(118, 75, 217, 1)];
    regbnt.layer.masksToBounds = YES;
    regbnt.layer.cornerRadius = 3;
    [regbnt addTarget:self action:@selector(registButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [mScrollView addSubview:regbnt];
    
    agreedBnt =creatXRButton(CGRectMake(10, VIEW_POINT_MAX_Y(regbnt) +20, 22, 22), nil, [UIImage imageNamed:@"确认regist.png"], nil) ;
    [agreedBnt addTarget:self action:@selector(agreedButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [mScrollView addSubview:agreedBnt];
    seleState = YES;
    
    UILabel *label = creatXRLable(@"我已阅读并同意", CGRectMake(VIEW_POINT_MAX_X(agreedBnt),VIEW_POINT_MIN_Y(agreedBnt)- 5,180,30));
    label.textAlignment =NSTextAlignmentLeft;
    label.textColor = RGBA(159, 159, 159, 1);
    label.font = [UIFont systemFontOfSize:16.0];
    [mScrollView addSubview:label];
    
    
    UILabel *label1 = creatXRLable(@"网络使用协议和隐私条款", CGRectMake(VIEW_POINT_MAX_X(agreedBnt),VIEW_POINT_MAX_Y(label)- 5,200,30));
    label1.textAlignment =NSTextAlignmentLeft;
    label1.textColor =[UIColor blueColor];
    label1.font = [UIFont systemFontOfSize:15.0];
    [mScrollView addSubview:label1];
}

#pragma mark BUTTON SEL
-(void)agreedButtonClick:(UIButton *)sender{
    if(seleState){
        seleState = NO;
        [agreedBnt setBackgroundImage:[UIImage imageNamed:@"确认2regist.png"] forState:UIControlStateNormal];
        regbnt.enabled =NO;
    }else{
        [agreedBnt setBackgroundImage:[UIImage imageNamed:@"确认regist.png"] forState:UIControlStateNormal];
        seleState = YES;
        regbnt.enabled = YES;
    }
}
-(void)registButtonClick:(UIButton *)sender{
    if (!IS_NOT_EMPTY(nameTextFiel.text)||!IS_NOT_EMPTY(passwordTextFiel.text)||!IS_NOT_EMPTY(secPassWordTextFiel.text)||!IS_NOT_EMPTY(emailTextFiel.text)) {
        [XDTools showTips:@"注册信息不能为空" toView:self.contentView];
    }else{
        NSString *userName = [nameTextFiel.text MD5Hash];
        NSString *passWord = [passwordTextFiel.text MD5Hash];
        
        
        if([passwordTextFiel.text isEqualToString:secPassWordTextFiel.text]){
            NSDictionary *dic = @{@"userName":userName,
                                  @"password":passWord,
                                  @"email":emailTextFiel.text,
                                  @"securitySignal":@"3765673"};
            
            [self getDataWithStr:@"1" parms:dic];
            [self theKeyboardTextHide];
        }else{
            [XDTools showTips:@"两次密码不一致" toView:self.contentView];
        }
    }
    
    
}
- (void)getDataWithStr:(NSString *)type  parms:(NSDictionary *)parms{
    
    __block  ASIFormDataRequest *request = [XDTools postRequestWithDict:parms API:API_REGISTER];
    
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.view];
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        NSDictionary *dict=[tempDic objectForKey:@"userinfo"];
        if([[tempDic objectForKey:@"result"]intValue] == 1){
            
            NSUserDefaults *userDef=[NSUserDefaults standardUserDefaults];
            [userDef setObject:dict forKey:kMMyUserInfo];
            [userDef synchronize];
            [XDTools showTips:@"注册成功" toView:self.view];
            
            if ([self.type isEqualToString:@"QQ"]) {
                //自动去绑定账号
                self.fetVC.userTf.text = nameTextFiel.text;
                self.fetVC.passWordTf.text = passwordTextFiel.text;
                [self.fetVC fetterWithData];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [self performSelector:@selector(getLogin) withObject:nil afterDelay:0.5];
                
            }
            
            
            
        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.view];
            
        }
    }];
    
    [request setFailedBlock:^{
        
        [XDTools hideProgress:self.view];
        NSError *error = [request error];
        DDLOG(@"error=%@",error);
    }];
    
    [XDTools showProgress:self.view];
    [request startAsynchronous];
    
}


- (void)getLogin{
    
    NSDictionary *dic2 = @{@"id":@"leepet_thread:api",@"action":@"login",@"username":nameTextFiel.text,@"password":passwordTextFiel.text};
    
    __weak  ASIHTTPRequest *request = [XDTools getRequestWithDict:dic2 API:@"plugin.php"];
    
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.view];
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        DDLOG(@"temdic == %@",tempDic);
        
        if([[tempDic objectForKey:@"result"]intValue] == 1){
           
            NSDictionary *subDict=[tempDic objectForKey:@"userinfo"];
            NSUserDefaults *userDef=[NSUserDefaults standardUserDefaults];
            
            
            [userDef setObject:subDict forKey:kMMyUserInfo];
            [userDef synchronize];
            
            [self.navigationController popToRootViewControllerAnimated:YES];
            
            
        }else{
            [XDTools showTips:[tempDic objectForKey:@"msg"] toView:self.view];
           
        }
        
    }];
    
    [request setFailedBlock:^{
        
        [XDTools hideProgress:self.view];
        NSError *error = [request error];
        DDLOG(@"error=%@",error);
    }];
    
    [XDTools showProgress:self.view];
    [request startAsynchronous];
    
}




-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self theKeyboardTextHide];
}
-(void)theKeyboardTextHide{
    [nameTextFiel resignFirstResponder];
    [passwordTextFiel resignFirstResponder];
    [secPassWordTextFiel resignFirstResponder];
    [emailTextFiel resignFirstResponder];
    
}
#pragma mark 重写父类的方法
- (void)backPrePage
{
   [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
   
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (!iPhone5) {
        if (textField == passwordTextFiel) {
            [UIView animateWithDuration:0.6 animations:^{
                mScrollView.contentOffset = CGPointMake(0, 40);
                [passwordTextFiel becomeFirstResponder];
            }];
        }else if (textField == secPassWordTextFiel) {
            [UIView animateWithDuration:0.6 animations:^{
                mScrollView.contentOffset = CGPointMake(0, 80);
                [secPassWordTextFiel becomeFirstResponder];
            }];
        }else if (textField == emailTextFiel) {
            [UIView animateWithDuration:0.6 animations:^{
                mScrollView.contentOffset = CGPointMake(0, 120);
                [emailTextFiel becomeFirstResponder];
            }];
        }
        
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [UIView animateWithDuration:.3 animations:^{
        mScrollView.contentOffset = CGPointMake(0, 0);
    }];
    return YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [emailTextFiel resignFirstResponder];
    [nameTextFiel resignFirstResponder];
    [passwordTextFiel resignFirstResponder];
    [secPassWordTextFiel resignFirstResponder];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
